package com.wxh.bomb.netty.design.masterwoker.core;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 任务分配者
 *
 * @author wxh
 * @date：2017.10.10
 */
public class Master {
    // 任务集合
    private ConcurrentLinkedQueue<Task> taskQueue = new ConcurrentLinkedQueue<Task>();

    // worker集合
    private ConcurrentHashMap<String, Thread> workers = new ConcurrentHashMap<String, Thread>();

    // worker并发的结果集
    private ConcurrentHashMap<String, Object> results = new ConcurrentHashMap<String, Object>();

    public Master(Worker worker, int workerCount) {
        // 每一个worker对象都需要有Master的引用 workQueue用于任务的领取，resultMap用于任务的提交
        worker.init(this.taskQueue, this.results);

        // 创建多个worker，并装载到worker集合中
        for (int i = 0; i < workerCount; i++) {
            workers.put("节点" + i, new Thread(worker));
        }
    }

    /**
     * 提交任务
     *
     * @param task
     */
    public void submit(Task task) {
        this.taskQueue.add(task);
    }

    /**
     * 执行任务
     */
    public void execute() {
        for (Map.Entry<String, Thread> me : workers.entrySet()) {
            me.getValue().start();
        }
    }

    /**
     * 获取任务的结果
     *
     * @return
     */
    public int getResult() {
        while (!isComplete()) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        int ret = 0;
        for (Map.Entry<String, Object> me : results.entrySet()) {
            //汇总的逻辑..
            ret += (Integer) me.getValue();
        }
        return ret;
    }

    /**
     * Worker是全部完成
     */
    private boolean isComplete() {
        for (Map.Entry<String, Thread> me : workers.entrySet()) {
            if (me.getValue().getState() != Thread.State.TERMINATED) {
                return false;
            }
        }
        return true;
    }

}
